package com.zjut.azhen.DBDesign.controllers;


import com.alibaba.fastjson.JSON;
import com.zjut.azhen.DBDesign.bean.RespBean;
import com.zjut.azhen.DBDesign.bean.Role;
import com.zjut.azhen.DBDesign.bean.User;
import com.zjut.azhen.DBDesign.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class LoginController {


   private final UserService userService;

    public LoginController(UserService userService){
        this.userService=userService;
    }
    @RequestMapping("/unlogin")
    public RespBean unlogin(){
        return RespBean.unlogged("未登录");
    }

    @RequestMapping("/unadmin")
    public RespBean unadmin(){return RespBean.unadmin("权限不足");}

    @RequestMapping("/logout")
    public RespBean logout(HttpSession session){
        session.removeAttribute("user");
        session.removeAttribute("role");
        //System.out.println(session.getAttribute("role"));
        return RespBean.ok("成功登出");
    }


    @PostMapping("/login")
    @ResponseBody
    public RespBean login(@RequestParam("username") String id
            ,@RequestParam("password") String password
            , HttpSession session){


        User user1=userService.getUserById(id);
        if(!id.equals(user1.getId())
        ||!password.equals(userService.getUserById(id).getPassword())){
            return RespBean.fail("用户名或密码错误");
        }
        //验证权限
        Role role=userService.getRoleById(id);
        //success
        session.setAttribute("user",user1);
        session.setAttribute("role",role);
        System.out.println("login: "+JSON.toJSONString(user1));
        Map<String,Object> map=new HashMap<>(2);
        map.put("user",user1);
        map.put("role",role);
        return RespBean.ok("登录成功",map);
    }



}
